import requests
from bs4 import BeautifulSoup

word = input("请输入要翻译的单词：")

url = "https://fanyi.baidu.com/"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"}

res = requests.get(url, headers=headers)
html = res.content

soup = BeautifulSoup(html, 'html.parser')

token = soup.select_one('body > div.wrap.clearfix')
if token:
    token = token['data-token']
else:
    print("无法获取token！")
sign = soup.select_one('#sign')['value']
cookie = res.cookies

data = {
    'kw': word,
    'from': 'en',
    'to': 'zh',
}
params = {
    'from': 'en',
    'to': 'zh',
    'token': token,
    'sign': sign,
}

api_url = "https://fanyi.baidu.com/v2transapi"
response = requests.post(api_url, data=data, params=params, headers=headers, cookies=cookie)
result = response.json()['trans_result']['data'][0]['dst']

print(f"{word}的翻译结果为：{result}")
